package com.gitee.wsl.doc.prosemirror.model.attr

import com.gitee.wsl.doc.prosemirror.exception.RangeError


// An object holding the attributes of a node.
typealias Attrs = Map<String, Any?>

val EmptyAttrs: Attrs = emptyMap()

// For node types where all attrs have a default value (or which don't have any attributes), build
// up a single reusable default attribute object, and use it for all nodes that don't specify
// specific attributes.
fun defaultAttrs(attrs: Map<String, Attribute>, includeNullValues: Boolean = false): Attrs {
    val res = mutableMapOf<String, Any?>()
    attrs.forEach { (key, value) ->
        if (includeNullValues || value.default != null) {
            res[key] = value.default
        }
    }
    return if (res.isEmpty()) EmptyAttrs else res.toMap()
}

fun checkAttrs(attrs: Map<String, Attribute>, values: Attrs, type: String, name: String) {
    values.keys.forEach { name ->
        if (name !in attrs) throw RangeError("Unsupported attribute $name for $type of type $name")
    }
    attrs.forEach { (name, attr) ->
        attr.validate?.invoke(values[name])
    }
}

// computeAttrs function not needed anymore - for correct round trip we don't combine attributes
// on creation
fun initAttrs(typeName: String, attrs: Map<String, AttributeSpec>?): Map<String, Attribute> {
    return attrs?.mapValues { (name, value) ->
        Attribute(typeName, name, value)
    } ?: emptyMap()
}
